package com.vtb.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.tencent.weibo.api.User_API;
import com.tencent.weibo.beans.OAuth;
import com.tencent.weibo.utils.OAuthClient;
import com.tencent.weibo.utils.WeiBoConst;
import com.vtb.base.VtbBaseServlet;
import com.vtb.entity.QqDetailInfo;
import com.vtb.entity.User;

/**
 * 1-获取授权的RequestToken 
 * 2-用RequestToken换取AccessToken 
 * 3-获取用户的基本信息
 *
 * @author Chen Tao
 * @date 2012-7-1 下午06:47:06
 */
@SuppressWarnings("serial")
public class QqOauthServlet extends VtbBaseServlet {
	private static final Log log = LogFactory.getLog(QqOauthServlet.class);

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String oauth_verifier = request.getParameter("oauth_verifier");
		OAuth oauth = (OAuth) request.getSession().getAttribute("qqOauth");
		QqDetailInfo qqDetailInfo = null;
		User_API user_API = new User_API();
		try {
			if (oauth == null || oauth_verifier == null) {
				throw new WtbException("授权RequestToken失败！");
			}
			oauth.setOauth_verifier(oauth_verifier);
			OAuthClient client = new OAuthClient();
			oauth = client.accessToken(oauth); // 用授权的RequestToken换取AccessToken
			if (oauth.getStatus() == 2) {
				throw new WtbException("授权AccessToken失败！");
			}
			// 获取用户详细信息
			String info = user_API.info(oauth,WeiBoConst.ResultType.ResultType_Json);
			JSONObject info_json = JSONObject.fromObject(info);
			int ok = info_json.getInt("ret");
			if (ok != 0) {
				throw new WtbException("获取用户信息失败！");
			}
			JSONObject data_json = info_json.getJSONObject("data");
			// 初始化 系统内的qqDetailInfo
			qqDetailInfo = new QqDetailInfo(oauth.getOauth_token(), oauth
					.getOauth_token_secret(), data_json.getString("name"),
					data_json.getString("email"), data_json.getString("nick"),
					data_json.getString("location"), "","");
			qqDetailInfo.setUser(new User(data_json.getString("nick"),data_json.getString("head")));
		} catch (Exception e) {
			log.error("QQ用户授权失败:", e);
			response.sendRedirect("error?err_code=1002");
			return;
		}
		super.doSession(request, response);
		lastMap.put("qq", qqDetailInfo);
		session.setAttribute("lastMap", lastMap);
		session.setAttribute("status", null);
		response.sendRedirect("last");
	}

}
